<template>
  <div>
    <a-modal
      v-model:visible="visible"
      @ok="handleOk"
      @cancel="handleCancel"
      :on-before-ok="beforeOkFn"
    >
      <template #title> {{ modalTitle }} </template>
      <div>
        <a-form
          :model="form"
          :style="{ width: '300px' }"
          :auto-label-width="true"
          ref="formRef"
        >
          <a-form-item
            field="name"
            label="商品分类名称"
            :rules="[{ required: true, message: '商品分类名称是必须的' }]"
          >
            <a-input v-model="form.name" placeholder="请输入商品分类名称" />
          </a-form-item>
        </a-form>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive } from 'vue';
  import {
    addCategoryAPI,
    editCategoryAPI,
    detailsCategoryAPI,
  } from '@/api/goods';
  import { Message } from '@arco-design/web-vue';
  // 父级传入子级的方法
  const emits = defineEmits(['resetFn']);
  const visible = ref(false);
  const modalType = ref('');
  const modalTitle = ref('');
  const handleCancel = () => {
    form.name = '';
    form.pid = null;
  };

  const formRef = ref();
  const beforeOkFn = async () => {
    const validate = await formRef.value.validate();
    return validate == null ? true : false;
  };
  const handleOk = async () => {
    try {
      if (modalType.value == 'add') {
        await addCategoryAPI(form);
        Message.success('新增商品分类成功');
      } else {
        let editForm: {
          id: number | null;
          name: string;
        } = {
          id: null,
          name: '',
        };
        editForm.id = form.pid;
        editForm.name = form.name;
        await editCategoryAPI(editForm);
      }
      emits('resetFn');
    } catch (error) {
      Message.error('操作分类失败');
    }
  };

  const form = reactive<{
    pid: number | null;
    name: string;
  }>({
    pid: null,
    name: '',
  });
  const openModal = (type: string, id: number) => {
    type == 'add'
      ? (modalTitle.value = '新增商品分类')
      : (modalTitle.value = '编辑商品分类');
    modalType.value = type;
    form.pid = id;
    if (type === 'edit') {
      detailsCategoryFn(id);
    }
    visible.value = true;
  };

  const detailsCategoryFn = async (id: number) => {
    try {
      const { data, code } = (await detailsCategoryAPI(id)).data;

      if (code !== 200) {
        Message.error('获取商品分类详情失败');
      } else {
        form.name = data.name;
      }
    } catch (error) {
      throw error;
    }
  };
  defineExpose({ openModal });
</script>

<style lang="scss" scoped></style>
